<template>
  <div class="admin-module admin-blog-detail">
    <el-form ref="formRef" :model="blogStore.newBlog"
             :inline="true" :rules="rules"
             class="blog-form">
      <el-form-item label="标题" name="title" prop="title">
        <el-input v-model="blogStore.newBlog.title"
                  :maxlength="30" show-word-limit clearable
                  style="width: 400px"/>
      </el-form-item>

      <el-form-item label="分类" name="category" prop="category">
        <el-select
            v-model="blogStore.newBlog.category"
            filterable allow-create placeholder="请选择分类" clearable
            @focus="focusCategoryEvent" style="width: 150px">
          <el-option
              v-for="(value, index) in blogStore.blogCategoryList"
              :key="index" :label="value.name" :value="value.name"/>
        </el-select>
      </el-form-item>

      <el-form-item label="置顶值">
        <el-input-number v-model="blogStore.newBlog.topValue"
                         :min="1" :max="10" style="width: 120px"/>
      </el-form-item>

      <el-form-item label="精品">
        <el-switch v-model="blogStore.newBlog.isGreat"/>
      </el-form-item>
    </el-form>

    <MdEditor v-model="blogStore.newBlog.content" @onUploadImg="onUploadImg"/>

    <div class="button-container">
      <el-button type="primary" @click="backClick">返回</el-button>
      <el-button type="primary"
                 :disabled="blogStore.newBlog.isApproved === 1"
                 @click="submitFormEvent(0)">保存为草稿</el-button>
      <el-button type="primary" @click="submitFormEvent(1)">发布</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useBlogStore } from '@/store/blog.ts'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { ElLoading, ElMessage, FormInstance, FormRules } from 'element-plus'
import { blogRules } from '@/utils/element/elRules.ts'
import { useRouter, useRoute } from 'vue-router'
import { validateBlogImage } from '@/utils/blog/blogUtil'
import { doUploadFile } from 'vue3-common/utils/fileUtil'
import { fileServiceUrl, serviceFileRootPath } from '@/utils'

const rules = reactive<FormRules>(blogRules)

const formRef = ref<FormInstance>()
const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

const focusCategoryEvent = async () => {
  await blogStore.queryBlogCategory()
}

onMounted(async () => {
  console.log('cxx')
  formRef.value?.clearValidate()

  const blogId = route.params.id as number
  if (blogId > 0) {
    blogStore.blogApiType = 'UPDATE'
    await blogStore.queryBlogById(route.params.id as number)
    blogStore.newBlog = blogStore.currentBlog
  } else {
    blogStore.blogApiType = 'ADD'
    blogStore.newBlog = blogStore.getEmptyBlog()
  }
})

/**
 * 校验博客
 */
const validateBlog = (): boolean => {
  if (blogStore.newBlog.content === '') {
    ElMessage.error('请输入博客内容')
    return false
  }

  return true
}

/**
 * 提交表单事件
 */
const submitFormEvent = (isApprove: number) => {
  // 表单校验
  formRef.value?.validate().then(async () => {
    blogStore.newBlog.isApproved = isApprove
    if (validateBlog()) {
      await blogStore.handleBlogApi()
      await router.push('/blog')
    }
  })
}

const onUploadImg = async (files: File[], callback) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在上传图片 请等待',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  if (validateBlogImage(files)) {
    const result = await doUploadFile(fileServiceUrl, files[0], blogStore.blogImagePath, false)
    // 显示在markdown中
    // 注意这里需要是数组的形式
    const urlArray = []
    urlArray.push({
      url: `${serviceFileRootPath}${result.url.replace(/\\/g, '/')}`,
      alt: '暂无图片',
      title: files[0].name
    })
    callback(urlArray)
  }

  loading.close()
}

const backClick = () => {
  router.push('/blog')
}
</script>

<style lang="scss">
.admin-blog-detail {
  position: relative;

  @media (max-width: 1200px) {
    .blog-form {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
    }
  }

  .md-editor {
    height: 80vh;
  }
}
</style>
